﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FerrScript.Builder
{
    public class ScriptBuilder
    {
        #region Singleton Code
               static ScriptBuilder mInstance = null;
        public static ScriptBuilder Instance
        {
            get { if (mInstance == null) mInstance = new ScriptBuilder(); return mInstance; }
        }
        #endregion

        #region Methods
        public  string BuildFunction(string aName, List<string> aArguments, List<BuilderBlock> aBlocks)
        {
            StringBuilder builder = new StringBuilder(aBlocks.Count * 5);

            // add the function signature
            if (aArguments != null)
            {
                builder.Append("(defun " + aName);
                for (int i = 0; i < aArguments.Count; i++)
                    builder.Append( " " + aArguments[i] );
                builder.AppendLine();
            }
            else
            {
                builder.AppendLine("(defun " + aName);
            }
            // add the contents of the script to i
            BuildScript(aBlocks, builder);
            // and the end of the script
            builder.Append    (")");

            return builder.ToString();
        }
        public  string BuildScript  (List<BuilderBlock> aBlocks)
        {
            StringBuilder builder = new StringBuilder(aBlocks.Count * 5);

            BuildScript(aBlocks, builder);

            return builder.ToString();
        }
        private void   BuildScript  (List<BuilderBlock> aBlocks, StringBuilder aBuilder)
        {
            int    open = 0;
            string tabs = "";

            for (int i = 0; i < aBlocks.Count; i++)
            {
                if (aBlocks[i].ParenType == ParenType.Close)
                {
                    open--;
                    tabs = tabs.Remove(0, 1);
                }

                aBuilder.AppendLine(tabs + aBlocks[i].ToString());

                if (aBlocks[i].ParenType == ParenType.Open || aBlocks[i].ParenType == ParenType.NeedsItem)
                {
                    open++;
                    tabs += "\t";
                }
                else if (aBlocks[i].ParenType == ParenType.SelfContained && i >= 1 && aBlocks[i - 1].ParenType == ParenType.NeedsItem)
                {
                    open--;
                    tabs = tabs.Remove(0, 1);
                    aBuilder.AppendLine(tabs + ")");
                }
            }
        }
        #endregion
    }
}
